package handler

import (
	"log"
	"strconv"
	"time"
	db "ulcdkey/db"
	"ulcdkey/tool"

	"github.com/labstack/echo/v4"
)

// 获取角色列表
func GetRoles(c echo.Context) error {
	var r ResponseResult
	t := time.Now()
	uid := tool.GetUid(c)

	role := new(db.Role)
	rs, err := role.GetRoles()
	if err != nil {
		log.Println("GetRoles:", err)
		r.Code = -1
		r.Msg = "获取数据失败,err=" + err.Error()
		return c.JSON(200, r)
	}
	r.Data = rs
	log.Println(c.Request().URL, "uid =", uid, "【耗时:", time.Now().Sub(t).Seconds(), "s】")
	return c.JSON(200, r)
}

// 添加角色
func AddRole(c echo.Context) error {

	c.Request().Header.Get("megaDataPlatform")
	var r ResponseResult
	t := time.Now()
	uid := tool.GetUid(c)

	userInfo := tool.GetVisitUserInfo(c)
	role := new(db.Role)
	role.Name = c.FormValue("name")
	err := role.AddRole(userInfo)
	if err != nil {
		log.Println("AddRole:", err)
		r.Code = -1
		r.Msg = "添加失败,err=" + err.Error()
		return c.JSON(200, r)
	}
	log.Println(c.Request().URL, "uid =", uid, "【耗时:", time.Now().Sub(t).Seconds(), "s】")
	return c.JSON(200, r)
}

// 获取角色的菜单权限展示
func GetMenuAuthTree(c echo.Context) error {
	var r ResponseResult
	t := time.Now()
	uid := tool.GetUid(c)
	idStr := c.FormValue("roleId")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		log.Println("GetAuthTree:", err)
		r.Code = -1
		r.Msg = "roleId参数错误,err" + err.Error()
		return c.JSON(200, r)
	}

	role := new(db.Role)

	as, err := role.GetMenuAuthTree(id)
	if err != nil {
		log.Println("GetAuthTree:", err)
		r.Code = -1
		r.Msg = "查询失败,err=" + err.Error()
		return c.JSON(200, r)
	}
	r.Data = as
	log.Println(c.Request().URL, "uid =", uid, "【耗时:", time.Now().Sub(t).Seconds(), "s】")
	return c.JSON(200, r)
}

// 更新角色的菜单权限
func UpdateRoleMenuAuth(c echo.Context) (err error) {
	var r ResponseResult

	role := new(db.Role)

	t := time.Now()
	uid := tool.GetUid(c)
	idStr := c.FormValue("roleId")
	role.Id, err = strconv.Atoi(idStr)
	if err != nil {
		log.Println("UpdateRoleMenuAuth:", err)
		r.Code = -1
		r.Msg = "roleId参数错误,err=" + err.Error()
		return c.JSON(200, r)
	}
	role.MenuAuth = c.FormValue("menuAuth")
	role.GameAuth = c.FormValue("gameAuth")
	role.PlatformAuth = c.FormValue("platformAuth")
	role.Name = c.FormValue("name")

	userInfo := tool.GetVisitUserInfo(c)

	err = role.UpdateRole(userInfo)
	if err != nil {
		log.Println("UpdateRoleMenuAuth:", err)
		r.Code = -1
		r.Msg = "更新失败,err=" + err.Error()
		return c.JSON(200, r)
	}
	log.Println(c.Request().URL, "uid =", uid, "【耗时:", time.Now().Sub(t).Seconds(), "s】")
	return c.JSON(200, r)
}
